package com.tstudy.laoshibang.base;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;

import com.baidu.frontia.FrontiaApplication;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.GeofenceClient;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.crashlytics.android.Crashlytics;
import com.tstudy.laoshibang.event.ChangeGroupEvent;
import com.tstudy.laoshibang.manager.GroupManager;
import com.tstudy.laoshibang.manager.UserManager;
import com.tstudy.laoshibang.mode.Address;
import com.tstudy.laoshibang.mode.City;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
//import com.crashlytics.android.Crashlytics;
//import io.fabric.sdk.android.Fabric;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;
import de.greenrobot.event.EventBus;
import io.fabric.sdk.android.Fabric;

/**
 * 应用程序基类
* @CopyRight weitaming.com
* @author wuyahui
* @E-mail wuyahui@ispied.com
* @version 1.0.0
* @Date @Date 2014年5月29日 下午5:02:53
 */
public class BaseApplication extends FrontiaApplication {
	public static Context mContext;
	public static Activity mCurrentActivity;
	public static BaseApplication mInstance = null;
	public static int mScreenWidth;
	public static int mScreenHeight;
	public static int mTitleBarHeight;
	public static int mStatusBarHeight;
	public static float mDensity;
	public static String mUAInfo;
	public static int mDensityDPI;
	public static int mMessageCount;
	public static Bitmap mCameraBM;
	public static Bitmap mHeaderBM;
	public static Address mCurrentAddress = new Address();
	
	public static class QzoneOAuthInfo{
		static public String accessToken;
		static public String openId;
		static public String expiresIn;
	}
//	public static User mUser;
//	public static LoginResult mLoginResult;
	public static LinkedList<String> mFollowingIds;
	public static LinkedList<String> mBookMarkIds;
	public static String mFilterParam;
	public static JSONArray mSourceConditionArray;
	public static int mSourceTotal;
	public static String mSortParam;
	public static String[] mColorArray;
	public static int mThemeColor;
	public static String mPushUserId;
	public static String mPushChannelId;
	public static String mUserNo;
	public static TGroup mCurrentGroup;
	public static User mCurrentUser;
	public static City mLocationCity;
	public static String mRegistSmsId;
	public static String mResetPasswordSmsId;
	public static String mBindMobileSmsId;
	
	public static boolean checkLogin(){
		if (TextUtils.isEmpty(mUserNo)) {
			mCurrentUser = UserManager.getInstance().getLoginUser();
			if (mCurrentUser != null) {
				mUserNo = mCurrentUser.getUserNo();
			}
		}
		return !TextUtils.isEmpty(mUserNo);
	}
	
	public static boolean checkGroup(){
		if (mCurrentGroup == null) {
			mCurrentGroup = (TGroup) GroupManager.getInstance().queryByFieldFirst("isSelect", "1");
		}
		return mCurrentGroup != null;
	}
	
	public static void clear(){
		mMessageCount = 0;
		QzoneOAuthInfo.accessToken = null;
		QzoneOAuthInfo.openId = null;
		QzoneOAuthInfo.expiresIn = null;
		mCurrentUser = null;
		mCurrentUser = null;
		mCurrentGroup = null;
		mFollowingIds = null;
	}
	
	@Override
	public void onCreate() {
//		ACRA.init(this);
//		ErrorReporter.getInstance().setReportSender(new IOReportSender(this));
		super.onCreate();
		Fabric.with(this, new Crashlytics());
		mContext = getApplicationContext();
		mInstance = this;
		SDKInitializer.initialize(this);
		initScreenInfo();
		initEngineManager();
//		initAmapLocation();
		mUAInfo = CommonUtil.getUserAgent();
		HttpManager.getInstance().initHttpInfo();
	}
	
	public static void setAppActivity(Activity activity) {
		mCurrentActivity = activity;
	}
	
	/**
	 * 获取屏幕信息	 */
	private void initScreenInfo(){
		DisplayMetrics dm = getResources().getDisplayMetrics();
		mScreenWidth = dm.widthPixels;
		mScreenHeight = dm.heightPixels;
		mDensity = dm.density;
		mDensityDPI = dm.densityDpi;
		LogUtil.d("--w==" + mScreenWidth +  ",h==" + mScreenHeight + ",d==" + mDensity + ",dpi==" + mDensityDPI);
		initStatusBar();
//		initTitleBar();
	}
	
	/**
	 * 获取状态栏高度	 */
	public  void initStatusBar(){
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            mStatusBarHeight = mContext.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
    }

	public LocationClient mLocationClient;
	public GeofenceClient mGeofenceClient;
	public MyLocationListener mMyLocationListener;
	public void initEngineManager() {
		mLocationClient = new LocationClient(this.getApplicationContext());
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		mGeofenceClient = new GeofenceClient(getApplicationContext());
	}
	
	/**
	 * 实现实位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			//Receive Location 
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append("\ncityCode : ").append(location.getCityCode());
			sb.append("\nCountryCode:").append(location.getCountryCode());
			sb.append("\nCountry:").append(location.getCountry());
			sb.append("\nDistrict:").append(location.getDistrict());
			sb.append("\nStreet:").append(location.getStreet());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				//运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
			}
			LogUtil.d("baidu location str===" + sb.toString());
			BaseApplication.mCurrentAddress.provinceName = location.getProvince();
			BaseApplication.mCurrentAddress.cityName = location.getCity();
			BaseApplication.mCurrentAddress.countyName = location.getDistrict();
			BaseApplication.mCurrentAddress.name = location.getAddrStr();
			BaseApplication.mCurrentAddress.latitude = location.getLatitude();
			BaseApplication.mCurrentAddress.longitude = location.getLongitude();
			
		}


	}
		
	public static void showToast(String msg) {
		Toast.makeText(mContext, msg, CONSTANT.SHOW_TOAST_LENGTH).show();
	}
	public static void showToast(String msg,int timeLength) {
		Toast.makeText(mContext, msg, timeLength).show();
	}

	public static void showToast(int stringId) {
		showToast(stringId,"");
	}
	
	public static void showToast(int stringId,String content) {
		Toast.makeText(mContext, mContext.getResources().getString(stringId)+ " " + content,CONSTANT.SHOW_TOAST_LENGTH).show();
	}
		
	public static String getResString(int stringId){
		return mContext.getResources().getString(stringId);
	}
	
	public static int getResDimen(int dimenId){
		return (int)mContext.getResources().getDimension(dimenId);
	}
	
	public static int getResColor(int corlorId){
		return mContext.getResources().getColor(corlorId);
	}
		
	private static List<Activity> activityStack = new ArrayList<Activity>();

	public static void clearStack() {
		int size = activityStack.size();
		for (int i = 0; i < size; i++) {
			activityStack.get(i).finish();
		}
		activityStack.clear();
	}

	public static void addStack(Activity activity) {
		activityStack.add(activity);
		mCurrentActivity = getTopActivity();
	}

	public static void removeStack(Activity activity) {
		activityStack.remove(activity);
		mCurrentActivity = getTopActivity();
	}

	public static void finishActivityInStack(int i) {
		if (0 <= i && i < activityStack.size()) {
			activityStack.get(i).finish();
			activityStack.remove(i);
		}

	}

	public static int getActivitySize() {
		return activityStack.size();
	}

	public static Activity getActivityInStack(int i) {
		if (0 <= i && i < activityStack.size()) {
			return activityStack.get(i);
		}
		return null;
	}
	
	public static Activity  getTopActivity(){
		return getActivityInStack(activityStack.size()-1);
	}
	
	public static void changeGroupAction(TGroup group){
		group.isSelect = 1;
		BaseApplication.mCurrentGroup = group;
		EventBus.getDefault().post(new ChangeGroupEvent());
		GroupManager.getInstance().clear(TGroup.class);
		GroupManager.instance.insert(group);
	}

}
